package com.qf.student.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Scanner;

/**
 * 数据库的打开和关闭
 */
public class DBMangaerUtils {

    private static String JDBC_URL = "jdbc:mysql://localhost:3306/2205-mysql";
    private static String USERNAME = "root";
    private static String PASSWORD = "root";
    private static String DRIVER_CLASS = "";

    static {
        // 1.加载指定文件的中的内容
        Properties properties = PropertiesUtils.loadProperties("jdbc.properties");

        // 2.从Properties获取属性
        USERNAME = properties.getProperty("jdbc.username");
        PASSWORD = properties.getProperty("jdbc.password");
        JDBC_URL = properties.getProperty("jdbc.url");
        DRIVER_CLASS = properties.getProperty("jdbc.driver");
        try {
            Class.forName(DRIVER_CLASS);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public static void close(AutoCloseable... args) {
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null) {
                try {
                    args[i].close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
